package com.ipan.poi.easyexcel.patch305;

import java.util.List;

import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.read.builder.AbstractExcelReaderParameterBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;

/**
 * ExcelReaderSheetBuilder补丁
 * 
 * @author iPan
 * @date 2022-01-30
 */
public class ExcelReaderSheetBuilder2 extends AbstractExcelReaderParameterBuilder<ExcelReaderSheetBuilder2, ReadSheet> {
    private ExcelReader2 excelReader;
    /**
     * Sheet
     */
    private ReadSheet readSheet;

    public ExcelReaderSheetBuilder2() {
        this.readSheet = new ReadSheet();
    }

    public ExcelReaderSheetBuilder2(ExcelReader2 excelReader) {
        this.readSheet = new ReadSheet();
        this.excelReader = excelReader;
    }

    /**
     * Starting from 0
     *
     * @param sheetNo
     * @return
     */
    public ExcelReaderSheetBuilder2 sheetNo(Integer sheetNo) {
        readSheet.setSheetNo(sheetNo);
        return this;
    }

    /**
     * sheet name
     *
     * @param sheetName
     * @return
     */
    public ExcelReaderSheetBuilder2 sheetName(String sheetName) {
        readSheet.setSheetName(sheetName);
        return this;
    }

    public ReadSheet build() {
        return readSheet;
    }

    /**
     * Sax read
     */
    public void doRead() {
        if (excelReader == null) {
            throw new ExcelGenerateException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
        }
        excelReader.read(build());
        excelReader.finish();
    }

    /**
     * Synchronous reads return results
     *
     * @return
     */
    public <T> List<T> doReadSync() {
        if (excelReader == null) {
            throw new ExcelAnalysisException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
        }
        SyncReadListener syncReadListener = new SyncReadListener();
        registerReadListener(syncReadListener);
        excelReader.read(build());
        excelReader.finish();
        return (List<T>)syncReadListener.getList();
    }

    @Override
    protected ReadSheet parameter() {
        return readSheet;
    }
    
    /**
     * 给外部调用者设置读取csv文件格式时候，能够设置CSVFormat格式使用；
     * CsvReadWorkbookHolder holder = (CsvReadWorkbookHolder) sheetBuilder.excelReader().analysisContext().readWorkbookHolder();
	 * holder.setCsvFormat(CSVFormat.DEFAULT.builder()
	 *			.setAutoFlush(true) // 实际autoFlush=false，默认情况下BufferWriter在close时候也会自动flush
	 *			.setTrim(true) // 自动对单元格做首尾trim
	 *			.setDelimiter("\t") // 分隔符
	 *			.build());
	 * sheetBuilder.doRead();
     */
    public ExcelReader2 excelReader() {
    	return excelReader;
    }
}